package com.googlecode.perfectable.messageable;

import static com.google.common.base.Preconditions.checkState;

import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;

public final class Stream {
	private static final String NAMESPACE_PREFIX = "stream";
	private static final String NAMESPACE = "http://googlecode.com/perfectable/messageable";
	private static final String ROOT_ELEMENT_LOCAL_NAME = "stream";
	
	public static void initializeWrite(XMLEventWriter writer, XMLEventFactory eventFactory) throws XMLStreamException {
		writer.add(eventFactory.createStartDocument());
		writer.add(eventFactory.createCharacters("\n"));
		writer.add(eventFactory.createStartElement(NAMESPACE_PREFIX, NAMESPACE, ROOT_ELEMENT_LOCAL_NAME));
		writer.add(eventFactory.createCharacters("\n"));
		writer.flush();
	}
	
	public static void initializeRead(XMLEventReader reader) throws XMLStreamException {
		StartElement startElement = reader.nextTag().asStartElement();
		checkState(ROOT_ELEMENT_LOCAL_NAME.equals(startElement.getName().getLocalPart()));
		checkState(NAMESPACE.equals(startElement.getName().getNamespaceURI()));
	}
	
	private Stream() {
		// constant container
	}
	
}
